import { cleanRules } from "./actions.mts";
import { debug, speedOnly } from "./buildConfig.mts";
import { data } from "./globalData.mts";
import {
  defaultValues,
  getCssLength,
  getSavedHosts,
  gmMenu,
  values,
} from "./gmBridge.mts";
import { logger, speed } from "./logger.mts";
import { hasSome, styleBoxes } from "./util.mts";

/**
 * 保存预存的 CSS
 * @async
 * @returns {Promise.<void>}
 */
async function saveCss(): Promise<void> {
  if (data.autoCleanSize > 0) {
    const cssLength = await getCssLength();
    debug &&
      !speedOnly &&
      logger("info", "总预存大小", cssLength, data.autoCleanSize);
    if (cssLength[1] >= data.autoCleanSize) {
      const saves = await getSavedHosts();
      for (const host of saves) {
        await values.css(null, host);
      }
      await gmMenu("count", cleanRules);
    }
  }
  const styles = {
    needUpdate: false,
    genHideCss: data.genHideCss,
    genExtraCss: data.genExtraCss,
    spcHideCss: data.spcHideCss,
    spcExtraCss: data.spcExtraCss,
  };
  debug &&
    !speedOnly &&
    logger("info", "此域名预存大小", JSON.stringify(styles).length, styles);
  await values.css(styles);
  return;
}

/**
 * 读取预存的 CSS
 * @async
 * @returns {Promise.<void>}
 */
async function readCss(): Promise<void> {
  const styles = (await values.css()) ?? defaultValues.css;
  if (!hasSome(Object.keys(styles), styleBoxes)) {
    await values.css(defaultValues.css);
    return;
  }
  if (debug && !speedOnly) {
    logger("data", {
      gHide: styles.genHideCss.length,
      gExtra: styles.genExtraCss.length,
      sHide: styles.spcHideCss.length,
      sExtra: styles.spcExtraCss.length,
      needUpd: styles.needUpdate,
    });
  }
  for (const sname of styleBoxes) {
    if (styles[sname].length > 0) {
      data.saved = true;
      data.update = styles.needUpdate ?? true;
      data[sname] = styles[sname];
    }
  }
  debug && speed("run3", "end");
  return;
}

export { readCss, saveCss };
